package com.rtline.business.advice;


import com.rtline.business.common.Result;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * <p>GlobalResponseBodyAdvice .结果的封装返回
 *
 * <p>change history:
 *
 * <pre>
 * date         defect       person          comments
 * --------------------------------------------------------------------------------
 * 2025/5/18    ********     Tao Ren    create file.
 * </pre>
 *
 * @author Tao Ren
 * @date 2025/5/18 19:14
 */
@ControllerAdvice
public class GlobalResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 检查返回值是否已经是 Result 类型或 String 类型
        return !Result.class.isAssignableFrom(returnType.getParameterType()) && !String.class.isAssignableFrom(returnType.getParameterType());
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 如果返回值不是 Result 类型且不是 String 类型，则包装为 Result 类型
        if (body == null) {
            return new Result<>(200, "操作成功", null);
        }
        return new Result<>(body);
    }
}
